package com.bw.gmall.app.dim;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.app.fure.TableProcessFunction;
import com.bw.gmall.bean.TableProcess;
import com.bw.gmall.utils.MyKafkaUtil;
import com.bw.gmall.utils.MyPhoenixSink;
import com.bw.gmall.utils.MysqlUtil;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class DimApp {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //读取的卡夫卡
        String topic = "topic_db";
        //写入的卡夫卡
        String groupId = "dim_app";
        DataStreamSource<String> ds = env.addSource(MyKafkaUtil.getFlinkKafkaConsumer(topic, groupId));
        //数据格式判断
        SingleOutputStreamOperator<JSONObject> filterJSONDS = ds.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                try {
                    JSONObject jsonObject = JSON.parseObject(value);
//                    保留新增及变化及初始化数据
                    String type = jsonObject.getString("type");
                    if (type.equals("insert") || type.equals("update") || type.equals("bootstrap-insert")) {
                        out.collect(jsonObject);
                    }
                } catch (Exception e) {
                    System.out.println("错误数据不是json数据:" + value);
                }
            }
        });
        //读取mysql表结构
        DataStream<String> mysqlDs =
                MysqlUtil.cdcMysql(env, "gmall_config", "table_process");        //创建广播流
        MapStateDescriptor<String, TableProcess> mapState =
                new MapStateDescriptor<>("mapState", String.class, TableProcess.class);        //把表结构插入广播流
        BroadcastStream<String> broadcastStream = mysqlDs.broadcast(mapState);
        //主流字段匹配广播流字段
        BroadcastConnectedStream<JSONObject, String> connect = filterJSONDS.connect(broadcastStream);
        //主流广播合并
        SingleOutputStreamOperator<JSONObject> dimDS = connect.process(new TableProcessFunction(mapState));

        //输出，写入Phoenix
        dimDS.print("最终结果--------->");
        dimDS.addSink(new MyPhoenixSink());
        //TODO 9. 启动任务
        env.execute();

    }
}
